﻿using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using RegexPractice.Properties;

namespace RegexPractice
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Regex_TextChanged(sender, e);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Settings.Default.input = this.tbSrc.Text;
            Settings.Default.pattern = this.tbRegex.Text;
            Settings.Default.Save();
        }

        private void tvDst_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            e.Cancel = true;
            if (e.Node.IsExpanded)
            {
                e.Node.Collapse();
            }
            else
            {
                e.Node.Expand();
            }
        }

        private void Regex_TextChanged(object sender, EventArgs e)
        {
            try
            {
                this.tvDst.Nodes.Clear();
                string pattern = this.tbRegex.Text;
                foreach (string input in this.tbSrc.Lines)
                {
                    TreeNode inputNode = CreateNode(input);
                    foreach (Match match in Regex.Matches(input, pattern, RegexOptions.None))
                    {
                        TreeNode matchNode = CreateNode(match.Value);
                        foreach (Group group in match.Groups)
                        {
                            TreeNode groupNode = CreateNode(group.Value);
                            foreach (Capture capture in match.Captures)
                            {
                                TreeNode captureNode = CreateNode(capture.Value);
                                groupNode.Nodes.Add(captureNode);
                            }
                            matchNode.Nodes.Add(groupNode);
                        }
                        inputNode.Nodes.Add(matchNode);
                    }
                    this.tvDst.Nodes.Add(inputNode);
                }
                this.tvDst.CollapseAll();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private TreeNode CreateNode(string text)
        {
            return new TreeNode(text)
            {
                BackColor = this.tvDst.BackColor,
                ForeColor = this.tvDst.ForeColor
            };
        }
    }
}